package com.getpebble.android.util;

import android.accounts.Account;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.auth.PblSessionManager;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.http.HttpRequestUtil;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Response;

public class UpgradeUtil {
    private static final String TAG = UpgradeUtil.class.getSimpleName();

    public static void processUpgrades(Context context) {
        if (context == null) {
            Trace.warning(TAG, "context is null");
            return;
        }
        PblPreferences prefs = new PblPreferences(context);
        long previousVersionCode = prefs.getLongData(PrefKey.INSTALLED_PEBBLE_APP_VERSION, -1);
        long currentVersionCode = 0;
        if (previousVersionCode == -1) {
            Trace.debug(TAG, "Not processing upgrades, oldversion is unknown.");
            return;
        }
        try {
            currentVersionCode = (long) context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
            prefs.setLongData(PrefKey.INSTALLED_PEBBLE_APP_VERSION, currentVersionCode);
        } catch (NameNotFoundException e) {
            Trace.error(TAG, "Could not get app version");
        }
        Trace.debug(TAG, "previoudVersion = " + previousVersionCode);
        Trace.debug(TAG, "currentVersion = " + currentVersionCode);
        if (previousVersionCode < 517) {
            Trace.debug(TAG, "Attempting to upgrade account id and uid...");
            PblSessionManager sessionManager = PebbleApplication.getSessionManager();
            if (sessionManager == null || sessionManager.peekAuthToken() == null) {
                Trace.error(TAG, "Failed to update user info: Session Manager was null!");
                return;
            }
            HttpRequestUtil.fetchMeData(context, false, sessionManager.peekAuthToken(), new FutureCallback<Response<JsonObject>>() {
                public void onCompleted(Exception e, Response<JsonObject> responseString) {
                    if (e != null) {
                        Trace.error(UpgradeUtil.TAG, "Failed to get account info", e);
                        return;
                    }
                    JsonObject user = PblSessionManager.getUserFromResponse(responseString);
                    if (user == null) {
                        Trace.error(UpgradeUtil.TAG, "Failed to update user id and uid. User was null!");
                    } else {
                        UpgradeUtil.updateAccountInfo(user.get("id").getAsString(), user.get("uid").getAsString());
                    }
                }
            }, 8000);
        }
        if (previousVersionCode < 530) {
            Trace.debug(TAG, "VERSION_2_2: sync bootconfig to v4 url");
            context.getContentResolver().delete(PblContentProviderUtil.getTableUri("boot_config"), null, null);
        }
    }

    private static void updateAccountInfo(String accountId, String accountUID) {
        PblSessionManager sessionManager = PebbleApplication.getSessionManager();
        Account account = sessionManager.getUserAccount();
        if (account != null) {
            Trace.debug(TAG, "Updating Account ID from " + sessionManager.getId(account) + " to " + accountId);
            sessionManager.setId(account, accountId);
            Trace.debug(TAG, "Updating Account UID from " + sessionManager.getUid(account) + " to " + accountUID);
            sessionManager.setUid(account, accountUID);
        }
    }
}
